package com.example.fenye.controller.forum;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.example.fenye.entity.forum.ForumUser;
import com.example.fenye.entity.forum.Post;
import com.example.fenye.entity.forum.Topic;
import com.example.fenye.service.forum.PostService;
import com.example.fenye.service.forum.TopicService;
import com.example.fenye.util.R;

@Controller
@RequestMapping(value="/forum/post")
public class PostController {
	@Resource
	PostService postService;
	
	@Resource
	TopicService topicService;
	
	
	@RequestMapping(value="toPostPost")
	public ModelAndView toPostPost(HttpServletRequest request, Long postTopic){
		ModelAndView mav = new ModelAndView("/forum/post/toPostPost");
		mav.addObject("postTopic",postTopic);
		return mav;
	}
	
	
	@ResponseBody
	@RequestMapping(value="/postPost")
	public R postPost(HttpServletRequest request, HttpSession session, String postContent, Long postTopic){
		Post post = new Post();
		post.setPostContent(postContent);
		post.setPostTopic(postTopic);
		post.setPostBy(((ForumUser)session.getAttribute("userLogin")).getUserId());
		post.setPostDate(new Date());
		
		Long postId = postService.addPost(post);
		if(postId!=null){
			return R.ok();
		}else{
			return R.error();
		}
	}
	
	
	@RequestMapping(value="/viewPost")
	public ModelAndView viewPost(HttpServletRequest request, Long topicid){
		ModelAndView mav = new ModelAndView("/forum/post/viewpostby_topic");
		Topic topic = topicService.getTopicById(topicid);
		List<Post> postsBelongTopic = postService.getPostListByTopicId(topicid);
		mav.addObject("topic", topic);
		mav.addObject("posts",postsBelongTopic);
		return mav;
	}
}
